/*
 * This file is Copyright 2002-2006 Loyola University Chicago,
 * Department of Computer Science and the Emerging Technologies Laboratory.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License via
 *    http://www.apache.org/licenses/LICENSE-2.0.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.citep.web.admin.users.client;

import java.util.HashMap;

import com.citep.web.gwt.module.BasePresentation;
import com.citep.web.gwt.module.Presentation;
import com.citep.web.gwt.validators.*;
import com.citep.web.gwt.widgets.StatusLabel;
import com.citep.web.gwt.dto.HistoryEncoder;
import com.citep.web.gwt.dto.UserDTO;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.ClickListener;


public class UserEntryPresentation extends BasePresentation implements Presentation {

	UserEntryApplication application;

	protected Grid inputGrid;
	protected Button submitButton;
	protected StatusLabel statusLabel;

	private TextBox emailText;
	private TextBox firstNameText;
	private TextBox lastNameText;
	private PasswordTextBox passwordText;
	private PasswordTextBox verifyPasswordText;
	
	protected VerticalPanel mainPanel;
	
	protected ListBox roleList;	
	protected Button createUserButton;
	protected Button userListButton;

	protected HashMap errorLabels = new HashMap();
	protected ValidatorGroup validator;

	protected ClickListener saveAction; //save account submit action
	protected ClickListener editAction; //edit account submit action
	
	public void clearFields() {
		firstNameText.setText("");
		lastNameText.setText("");
		emailText.setText("");
		passwordText.setText("");
		verifyPasswordText.setText("");
	}
	
	public void setSaveState() {
		titleLabel.setText("Create new user");
		clearFields();
		
		submitButton.setText("Save");
		submitButton.removeClickListener(getEditAction());
		submitButton.removeClickListener(getSaveAction());
		submitButton.addClickListener(getSaveAction());
		submitButton.setEnabled(true);
		
	}
	
	public void setEditState() {
		titleLabel.setText("Edit user");
		clearErrors();
		submitButton.setText("Update");
		submitButton.removeClickListener(getSaveAction());
		submitButton.removeClickListener(getEditAction());
		submitButton.addClickListener(getEditAction());
		submitButton.setEnabled(true);
	}
	
	public void setUserData(UserDTO user) {
		if(user != null) {
			firstNameText.setText(user.getFirstName());
			lastNameText.setText(user.getLastName());
			emailText.setText(user.getEmail());
			passwordText.setText(user.getPassword());
			verifyPasswordText.setText(user.getPassword());
			setListValue(roleList,user.getRoleName());
		}
	}

	public void getUserData(UserDTO user) {
		if(user != null) {
			user.setFirstName(firstNameText.getText());
			user.setLastName(lastNameText.getText());
			user.setEmail(emailText.getText());
			user.setPassword(passwordText.getText());
			user.setRoleName(getListSelectedValue(roleList));
		}
	}
	
	public StatusLabel getStatusLabel() {
		if(statusLabel == null) {
			statusLabel = new StatusLabel();
			statusLabel.setStyleName("status_label");
			statusLabel.setVisible(false);
		}

		return statusLabel;
	}

	
	
	public void addWidgetToInputGrid(Grid g, String description, Widget w) {
		int rows = g.getRowCount();
		int cols = g.getColumnCount();
		
		g.resize(rows+1,cols);
		g.setText(rows, 0, description);
		g.setWidget(rows,1, w);
		g.getCellFormatter().setStyleName(rows, 0, "input_cell");
		g.getCellFormatter().setStyleName(rows, 1, "input_cell");

	}
		
	public void displayStatus(String text, int seconds) {
		getStatusLabel().setText(text);
		getStatusLabel().show(seconds);
	}
	
	public void addRole(String roleName) {
		getRoleList().addItem(roleName);
	}
	
	public void clearRoleList() {
		getRoleList().clear();
	}

	protected Button getCreateUserButton() {
		if(createUserButton == null) {
			createUserButton = new Button("Create User");
			createUserButton.setStyleName("form_button");
			createUserButton.addClickListener(new ClickListener() {
				public void onClick(Widget w) {
					String token = HistoryEncoder.encode("user_entry",null);
					History.newItem(token);
				}
			});
		}
		
		return createUserButton;
	}
	
	protected Button getUserListButton() {
		if(userListButton == null) {
			userListButton = new Button("List Users");
			userListButton.setStyleName("form_button");
			userListButton.addClickListener(new ClickListener() {
				public void onClick(Widget w) {
					String token = HistoryEncoder.encode("user_list",null);
					History.newItem(token);
				}
			});
		}
		
		return userListButton;
	}
	
	protected ListBox getRoleList() {
		if(roleList == null) {
			roleList = new ListBox();
		}
		return roleList;
	}
	
	public Widget getContext() {
		VerticalPanel p = new VerticalPanel();
		p.setStyleName("context_table");
		p.setSpacing(0);
		
		
		p.add(getCreateUserButton());
		p.add(getUserListButton());
		
		return p;

	}

	public Widget getMainPanel() {
		return mainPanel;
	}

	public void setApplication(UserEntryApplication application) {
		this.application = application;
	}

	public Grid getInputGrid() {
		if(inputGrid == null) {
			inputGrid = new Grid(0,2);
			inputGrid.setCellPadding(0);
			inputGrid.setCellSpacing(0);
			
			inputGrid.setStyleName("input_grid");
			
			addValidationLabelToGrid(inputGrid, createErrorLabel("User.firstName"));

			firstNameText = createTextBox("form_textentry",20);
			addWidgetToInputGrid(inputGrid,"First Name:", firstNameText);
			
			addValidationLabelToGrid(inputGrid, createErrorLabel("User.lastName"));

			lastNameText = createTextBox("form_textentry", 20);
			addWidgetToInputGrid(inputGrid,"Last Name:", lastNameText);
			
			addValidationLabelToGrid(inputGrid, createErrorLabel("User.email"));
			
			emailText = createTextBox("form_textentry", 30);
			addWidgetToInputGrid(inputGrid, "Email:", emailText);
			
			addValidationLabelToGrid(inputGrid, createErrorLabel("User.password"));
			
			passwordText = createPasswordTextBox("form_textentry",10);
			addWidgetToInputGrid(inputGrid, "Password:", passwordText);

			addValidationLabelToGrid(inputGrid, createErrorLabel("User.verifyPassword"));

			verifyPasswordText = createPasswordTextBox("form_textentry",10);
			addWidgetToInputGrid(inputGrid, "Verify Password:", verifyPasswordText);
			
			addValidationLabelToGrid(inputGrid, createErrorLabel("User.role"));
			addWidgetToInputGrid(inputGrid, "Role:", getRoleList());
						
			int rows = inputGrid.getRowCount();
			int cols = inputGrid.getColumnCount();
			
			inputGrid.resize(rows+1,cols);
		}
		
		setValidation();
		return inputGrid;
	}

	
	public void setValidation() {
		if(validator == null)
			validator = new ValidatorGroup();
		
		ValidationErrorListener listener = new ValidationErrorListener();
		
		validator.addValidator("User.firstName", firstNameText, new RequiredValidator(listener,"Please enter a valid name"));
		validator.addValidator("User.email", emailText, new RequiredValidator(listener,"Please enter a valid email"));
		validator.addValidator("User.password", passwordText, new RequiredValidator(listener,"Please enter a valid password"));
		validator.addValidator("User.verifyPassword", verifyPasswordText, new RequiredValidator(listener,"Please verify the password"));
		validator.addValidator("User.verifyPassword", passwordText, new PasswordVerificationValidator(listener,verifyPasswordText,"Passwords do not match"));
		validator.addValidator("User.email", emailText, new EmailValidator(listener, "Please enter a valid email"));
	}

	protected ClickListener getSaveAction() {
		if(saveAction == null) {
			saveAction = new ClickListener() {
				public void onClick(Widget w) {
					clearErrors();
					if(validator.validate()) {
						String selectedRole = getListSelectedValue(getRoleList());
						application.addUser(firstNameText.getText(), lastNameText.getText(), emailText.getText(), passwordText.getText(),selectedRole);
					}
				};
			};
		}
		return saveAction;
	}
	
	protected ClickListener getEditAction() {
		if(editAction == null) {
			editAction = new ClickListener() {
				public void onClick(Widget w) {
					clearErrors();
					if(validator.validate()) {
						application.saveCurrentUser();
					}
				};
			};
		}
		return editAction;
	}
	
	
	protected Button getSubmitButton() {
		if(submitButton == null) {
			submitButton = new Button("Save");
			submitButton.setStyleName("form_big_button");
			
			submitButton.addClickListener(getSaveAction());
		}

		return submitButton;
	}

	public UserEntryPresentation() {
		mainPanel = new VerticalPanel();
		mainPanel.setWidth("100%");
		
		getTitleLabel().setText("Create user account");
		mainPanel.add(getTitlePanel());
		
		mainPanel.add(getInputGrid());
		
		mainPanel.add(getSubmitButton());
		mainPanel.setCellHorizontalAlignment(getSubmitButton(), HasHorizontalAlignment.ALIGN_CENTER);
		
		mainPanel.add(getStatusLabel());
		mainPanel.setCellHorizontalAlignment(getStatusLabel(), HasHorizontalAlignment.ALIGN_CENTER);
		
	}
}
 